package com.yeren.czbk.basic.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.yeren.czbk.basic.dao.TuserDao;
import com.yeren.czbk.basic.entity.Tuser;
import com.yeren.czbk.util.HibernateUtil;
import com.yeren.czbk.util.QueryRusult;

public class TuserDaoImpl implements TuserDao{

	public void save(Tuser user) {
		Session session = HibernateUtil.OpenSession();
		Transaction tx=null;
		try {
			tx = session.beginTransaction();
			session.save(user);
			tx.commit();
		} catch (RuntimeException e) {
			tx.rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
		
	}

	public void delete(Integer id) {
		Session session = HibernateUtil.OpenSession();
		Transaction tx=null;
		Tuser user=null;
		try {
			tx = session.beginTransaction();
			//操作
			Object o=session.get(Tuser.class, id);
			session.delete(o);//删除的事实体对象
			tx.commit();
		} catch (RuntimeException e) {
			tx.rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
		
	}

	public void update(Tuser user) {
		Session session = HibernateUtil.OpenSession();
		Transaction tx=null;
		try {
			tx = session.beginTransaction();
			session.update(user);
			tx.commit();
		} catch (RuntimeException e) {
			tx.rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
		
	}

	public Tuser getById(Integer id) {
		Session session = HibernateUtil.OpenSession();
		Transaction tx=null;
		Tuser user=null;
		try {
			tx = session.beginTransaction();
			user = (Tuser)session.get(Tuser.class, id);
			tx.commit();
		} catch (RuntimeException e) {
			tx.rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
		return user;
		
	}

	public List<Tuser> findAll() {
		Session session = HibernateUtil.OpenSession();
		Transaction tx=null;
		List<Tuser> list=null;
		try {
			String hql="from Tuser";
			tx = session.beginTransaction();
			//操作
			Query query=session.createQuery(hql);
			list = query.list();//使用HQL查询操作
			tx.commit();
		} catch (RuntimeException e) {
			tx.rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
		return list;
	}

	public QueryRusult findAll(Integer firstResult, Integer maxResult) {
		Session session = HibernateUtil.OpenSession();
		Transaction tx=null;
		List<Tuser> list=null;
		Long count=null;
		try {
			String hql="from Tuser";
			tx = session.beginTransaction();
			//操作
			Query query=session.createQuery(hql);
			query.setFirstResult(firstResult);
			query.setMaxResults(maxResult);
			list = query.list();//使用HQL查询操作
			//查询总记录数
			count = (Long)session.createQuery("select count(*) from Tuser").uniqueResult();
			
			tx.commit();
			
		} catch (RuntimeException e) {
			tx.rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
		return  new QueryRusult(count.intValue(), list);
	}



}
